package com.eg366.nioLearn.simple;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 读写结合 读readandshow.txt写入到writenio.txt中
 * 使用一个缓冲区，不断重复执行：读、写、读、写
 */
public class NioReadWrite {

	public static void main(String[] args) throws IOException {
		FileInputStream fis = new FileInputStream(Thread.currentThread().getContextClassLoader().getResource("")
				.getPath()
				+ "readandshow.txt");
		FileOutputStream fos = new FileOutputStream(Thread.currentThread().getContextClassLoader().getResource("")
				.getPath()
				+ "writenio.txt");
		FileChannel readChannel = fis.getChannel();
		FileChannel writeChannel = fos.getChannel();
		
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		
		while (readChannel.read(buffer) != -1) {
			buffer.flip();
			writeChannel.write(buffer);
			buffer.clear();
		}
		
		readChannel.close();
		writeChannel.close();
		fis.close();
		fos.close();
	}
}
